<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="180px">
      <el-form-item label="炮筒名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入炮筒名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="所属支公司" prop="company">
        <el-select 
          v-model="queryParams.company" 
          placeholder="请选择所属支公司" 
          style="width:100%"
          @change="handleCompanyChange"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_dept_dept_name"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="光缆名称" prop="cableId">
        <el-select
          v-model="queryParams.cableId"
          filterable
          clearable
          placeholder="请选择光缆名称"
          style="width: 100%"
          :loading="loadingCables"
        >
          <el-option
            v-for="item in filteredCableOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="炮筒顺序" prop="sequence">
        <el-input
          v-model="queryParams.sequence"
          placeholder="请输入炮筒顺序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="搜索距离(km)" prop="height">
        <el-input
          v-model="queryParams.height"
          placeholder="请输入距离(km)"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <template slot="append">km</template>
        </el-input>
      </el-form-item>

      <el-form-item style="text-align: right;">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:manholes:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:manholes:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:manholes:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:manholes:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="manholesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="炮筒名称" align="center" prop="name" />
      <el-table-column label="光缆名称" align="center">
        <template slot-scope="scope">
          {{ getCableName(scope.row.cableId) }}
        </template>
      </el-table-column>
      <el-table-column label="所属支公司" align="center">
        <template slot-scope="scope">
          {{ getCableCompany(scope.row.cableId) || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="炮筒类型" align="center" prop="type" />
      <el-table-column label="炮筒状态" align="center" prop="status" />
      <el-table-column label="炮筒顺序" align="center" prop="sequence" />
      <el-table-column label="与上点距离(km)" align="center" prop="height" />
      <!-- <el-table-column label="累计距离(km)" align="center">
        <template slot-scope="scope">
          {{ scope.row.cumulativeheight !== undefined ? scope.row.cumulativeheight : '-' }}
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:manholes:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:manholes:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改炮筒对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="炮筒名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入炮筒名称" />
        </el-form-item>
        <el-form-item label="炮筒经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入炮筒经度" />
        </el-form-item>
        <el-form-item label="炮筒纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入炮筒纬度" />
        </el-form-item>
        <el-form-item label="光缆名称" prop="cableId">
          <el-select
            v-model="form.cableId"
            filterable
            clearable
            placeholder="请选择光缆名称"
            style="width: 100%"
            :loading="loadingCables"
          >
            <el-option
              v-for="item in allCableOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="炮筒顺序" prop="sequence">
          <el-input-number 
            v-model="form.sequence" 
            placeholder="请输入炮筒顺序"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listManholes, getManholes, delManholes, addManholes, updateManholes } from "@/api/system/manholes";
import { listCables } from "@/api/system/cables";

export default {
  name: "Manholes",
  dicts: ['sys_dept_dept_name'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 炮筒表格数据
      manholesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        longitude: null,
        latitude: null,
        type: null,
        status: null,
        cableId: null,
        sequence: null,
        height: null,
        company: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "炮筒名称不能为空", trigger: "blur" }
        ],
        longitude: [
          { required: true, message: "炮筒经度不能为空", trigger: "blur" }
        ],
        latitude: [
          { required: true, message: "炮筒纬度不能为空", trigger: "blur" }
        ],
        sequence: [
          { required: true, message: "炮筒顺序不能为空", trigger: "blur" },
          { type: "number", message: "必须为数字值" }
        ],
        cableId: [
          { required: true, message: "请选择光缆名称", trigger: "change" }
        ]
      },
      // 光缆相关数据
      loadingCables: false,
      allCables: [], // 所有光缆数据
      filteredCableOptions: [], // 筛选后的光缆选项
      cableCompanyMap: new Map(), // 光缆ID到支公司的映射
      allCableOptions: [] // 所有光缆选项（用于表单）
    };
  },
  created() {
    this.getList();
    this.loadAllCables();
  },
  methods: {
    /** 加载所有光缆数据 */
    loadAllCables() {
      this.loadingCables = true;
      listCables({ pageSize: 1000 }).then(response => {
        this.allCables = response.rows;
        // 建立映射关系
        response.rows.forEach(cable => {
          this.cableCompanyMap.set(cable.id, cable.company);
        });
        // 初始化所有选项
        this.allCableOptions = response.rows.map(cable => ({
          value: cable.id,
          label: cable.name
        }));
        this.filteredCableOptions = [...this.allCableOptions];
        this.loadingCables = false;
      }).catch(() => {
        this.loadingCables = false;
      });
    },

    /** 支公司选择变化时 */
    handleCompanyChange(company) {
      this.queryParams.cableId = null; // 清空已选光缆
      
      if (company) {
        // 筛选该支公司的光缆
        this.filteredCableOptions = this.allCables
          .filter(cable => cable.company === company)
          .map(cable => ({
            value: cable.id,
            label: cable.name
          }));
      } else {
        // 显示全部光缆
        this.filteredCableOptions = [...this.allCableOptions];
      }
    },

    /** 获取炮筒列表 */
    getList() {
      this.loading = true;
      // 移除company参数，因为后端不支持
      const { company, height, ...apiParams } = this.queryParams;
      
      listManholes(apiParams).then(response => {
        let filteredData = response.rows;
        // 前端过滤：按支公司
        if (company) {
          filteredData = filteredData.filter(manhole => {
            return this.cableCompanyMap.get(manhole.cableId) === company;
          });
        }
        
        // 前端过滤：按距离
        if (height) {
          filteredData = this.filterByheight(filteredData, parseFloat(height));
        }
        
        this.manholesList = filteredData.map(item => ({
          ...item,
          cableName: this.getCableName(item.cableId)
        }));
        
        this.total = response.total; // 使用过滤后的数量
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 根据光缆ID获取光缆名称 */
    getCableName(cableId) {
      if (!cableId) return '-';
      const cable = this.allCables.find(item => item.id === cableId);
      return cable ? cable.name : '-';
    },

    /** 根据光缆ID获取支公司名称 */
    getCableCompany(cableId) {
      if (!cableId) return null;
      return this.cableCompanyMap.get(cableId);
    },

    /** 计算两点间距离(km) - Haversine公式 */
    calculateheight(lng1, lat1, lng2, lat2) {
      const R = 6371; // 地球半径(km)
      const dLat = this.deg2rad(lat2 - lat1);
      const dLng = this.deg2rad(lng2 - lng1);
      
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * 
        Math.sin(dLng/2) * Math.sin(dLng/2);
      
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      return R * c;
    },

    /** 角度转弧度 */
    deg2rad(deg) {
      return deg * (Math.PI/180);
    },

    /** 根据距离过滤炮筒 */
    filterByheight(manholes, maxheight) {
      // 按光缆分组
      const groupedByCable = manholes.reduce((acc, manhole) => {
        if (!acc[manhole.cableId]) {
          acc[manhole.cableId] = [];
        }
        acc[manhole.cableId].push(manhole);
        return acc;
      }, {});

      const result = [];
      
      // 处理每条光缆的炮筒
      Object.values(groupedByCable).forEach(cableManholes => {
        // 按顺序排序
        const sortedManholes = [...cableManholes].sort((a, b) => a.sequence - b.sequence);
        
        let cumulativeheight = 0;
        let addedExtraManhole = false;
        
        // 计算累计距离
        for (let i = 0; i < sortedManholes.length; i++) {
          const current = sortedManholes[i];
          
          if (i > 0) {
            const prev = sortedManholes[i - 1];
            const segmentheight = this.calculateheight(
              prev.longitude, prev.latitude,
              current.longitude, current.latitude
            );
            cumulativeheight += segmentheight;
          }
          
          if (cumulativeheight <= maxheight) {
            result.push({
              ...current,
              cumulativeheight: parseFloat(cumulativeheight.toFixed(2))
            });
          } else if (!addedExtraManhole) {
            result.push({
              ...current,
              cumulativeheight: parseFloat(cumulativeheight.toFixed(2))
            });
            addedExtraManhole = true;
            break;
          } else {
            break;
          }
        }
      });

      return result;
    },

    // 重置表单
    reset() {
      this.form = {
        id: null,
        name: null,
        longitude: null,
        latitude: null,
        type: null,
        status: null,
        cableId: null,
        sequence: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: null,
        longitude: null,
        latitude: null,
        type: null,
        status: null,
        cableId: null,
        sequence: null,
        height: null,
        company: null
      };
      this.filteredCableOptions = [...this.allCableOptions];
      this.getList();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加炮筒";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getManholes(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改炮筒";
      });
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateManholes(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addManholes(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除炮筒编号为"' + ids + '"的数据项？').then(() => {
        return delManholes(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/manholes/export', {
        ...this.queryParams
      }, `manholes_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 15px;
}

.el-form--inline .el-form-item {
  margin-right: 10px;
}

.el-button + .el-button {
  margin-left: 10px;
}

.el-table .cell .el-button--text {
  padding: 0;
  margin: 0 5px;
}
</style>